//
//  UsingAVKitViewController.swift
//  MyVideo
//
//  Created by han on 2021/4/20.
//

import UIKit
import AVKit

class UsingAVKitViewController: UITableViewController {
    let items = ["Presenting Full Screen", "Embedding Inline"]
    let playbackController = VideoPlaybackController()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        playbackController.prepareForPlayback()
        playbackController.videoItemDelegate = self
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        transitionCoordinator?.animate(alongsideTransition: nil, completion: { (context) in
            if !context.isCancelled {
                self.playbackController.removeAllEmbeddedViewControllers()
            }
        })
    }
}

extension UsingAVKitViewController {

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        guard let cell = sender as? UITableViewCell, let videoBrowser = segue.destination as? VideoBrowserViewController else { return }
        videoBrowser.title = cell.textLabel?.text
        videoBrowser.playbackController = playbackController
        videoBrowser.wantsFullScreen = segue.identifier == "ShowSampleFullScreenSegue" ? true : false
    }
}

extension UsingAVKitViewController: VideoPlayerViewControllerCoordinatorDelegate {
    func playerViewControllerCoordinator(_ coordinator: VideoPlayerViewControllerCoordinator, restoreUIForPIPStop completion: @escaping (Bool) -> Void) {
        if coordinator.playerViewControllerIfLoaded?.parent == nil {
            if let navigationController = navigationController {
                coordinator.restoreFullScreen(from: navigationController) {
                    completion(true)
                }
            } else {
                completion(false)
            }
        } else {
            completion(true)
        }
    }
    
    func playerViewControllerCoordinatorWillDismiss(_ coordinator: VideoPlayerViewControllerCoordinator) {
        if let index = playbackController.indexPath(for: coordinator), let contentBrowser = navigationController?.topViewController as? VideoBrowserViewController,
           !contentBrowser.collectionView.fullyShowsItem(at: index) {
            contentBrowser.collectionView.scrollToItem(at: index, at: .top, animated: false)
        }
    }
    
}

private extension UICollectionView {
    /// 判断是否完全显示
    func fullyShowsItem(at indexPath: IndexPath) -> Bool {
        if let attributes = layoutAttributesForItem(at: indexPath) {
            return bounds.inset(by: safeAreaInsets).contains(attributes.frame)
        }
        return false
    }
}

/*
 let player = AVPlayer(url: url)
 let controller = AVPlayerViewController()
 controller.player = player
 present(controller, animated: true) {
    player.play()
 }
 */
